package co.edu.eam.iso.view;

import java.awt.Component;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.math.BigDecimal;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileNameExtensionFilter;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import co.edu.eam.iso.enums.CharacteristicEnum;
import co.edu.eam.iso.enums.IconEnum;
import co.edu.eam.iso.enums.RankEnum;
import co.edu.eam.iso.evaluated.ProductEvaluated;
import co.edu.eam.iso.logger.Logger;
import co.edu.eam.iso.poi.ExcelGenerator;
import co.edu.eam.iso.view.treetable.JTreeTable;
import co.edu.eam.iso.view.treetable.Model;

public class EvaluationModal extends JDialog {

	private static final long serialVersionUID = 1L;
	
	private static final int SPACE = 5;
	private static final int LABEL_WIDTH = 90;
	private static final int LABEL_HEIGHT = 16;
	private static final int TEXTFIELD_WIDTH = 50;
	private static final int TEXTFIELD_HEIGHT = 25;	
	
	/**
	 * Content pane.
	 */
	private JPanel contentPane;
	
	private Component parent;
	private JTextField txtReliabilityQuality;
	private JTextField txtEfficiencyQuality;
	private JTextField txtPortabilityQuality;
	private JTextField txtFunctionalityQuality;
	private JTextField txtUsabilityQuality;
	private JTextField txtMaintainabilityQuality;
	private JTextField txtProductQuality;
	
	private ProductEvaluated productEvaluated;
	
	private int[][] coordinates;

	/**
	 * Create the dialog.
	 */
	public EvaluationModal(Component parent, ProductEvaluated productEvaluated) {
		this.parent = parent;
		this.productEvaluated = productEvaluated;
		this.coordinates = new int[productEvaluated.getCharacteristics().size()][];
	
		calculateCoordinates();
		initialize();
	}

	private void initialize() {
		setTitle("ISO 9126-1 - Resultado de la evaluación");
		setBounds(100, 100, 888, 380);
		setLocationRelativeTo(null);
		setModalityType(ModalityType.APPLICATION_MODAL);
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		setResizable(false);
		setLocationRelativeTo(parent);
						
		contentPane = new JPanel();
		contentPane.setLayout(null);		
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		
		JPanel panelCharacteristicsQuality = new JPanel();
		panelCharacteristicsQuality.setLayout(null);
		panelCharacteristicsQuality.setBounds(442, 52, 430, 136);
		panelCharacteristicsQuality.setBorder(new TitledBorder(null,
				"Calidad por caracter\u00EDstica", TitledBorder.LEADING,
				TitledBorder.TOP, null, null));
		contentPane.add(panelCharacteristicsQuality);
		
		int count = -1;	
		if (productEvaluated.getCharacteristics().containsKey(
				CharacteristicEnum.FUNCTIONALITY)) {
			createFunctionalityQuality(panelCharacteristicsQuality,
					coordinates[++count]);
		}

		if (productEvaluated.getCharacteristics().containsKey(
				CharacteristicEnum.RELIABILITY)) {
			createReliabilityQuality(panelCharacteristicsQuality,
					coordinates[++count]);
		}

		if (productEvaluated.getCharacteristics().containsKey(
				CharacteristicEnum.USABILITY)) {
			createUsabilityQuality(panelCharacteristicsQuality,
					coordinates[++count]);
		}

		if (productEvaluated.getCharacteristics().containsKey(
				CharacteristicEnum.EFFICIENCY)) {
			createEfficiencyQuality(panelCharacteristicsQuality,
					coordinates[++count]);
		}

		if (productEvaluated.getCharacteristics().containsKey(
				CharacteristicEnum.MAINTAINABILITY)) {
			createMaintainabilityQuality(panelCharacteristicsQuality,
					coordinates[++count]);
		}

		if (productEvaluated.getCharacteristics().containsKey(
				CharacteristicEnum.PORTABILITY)) {
			createPortabilityQuality(panelCharacteristicsQuality,
					coordinates[++count]);
		}
				
		JButton btnResume = new JButton();
		btnResume.setBounds(442, 199, 35, 35);
		contentPane.add(btnResume);
		btnResume.setIcon(getIcon(IconEnum.REPORT));
		btnResume.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				ExcelGenerator exporter = new ExcelGenerator();
				HSSFWorkbook book = exporter.generateExcel(productEvaluated);				
				save(book);
			}
		});
		
		JLabel lblProductQuality = new JLabel("Calidad total del producto:");
		lblProductQuality.setFont(new Font("Tahoma", Font.BOLD, 12));
		lblProductQuality.setBounds(442, 14, 170, 14);
		contentPane.add(lblProductQuality);
		
		txtProductQuality = new JTextField();
		txtProductQuality.setBounds(622, 10, 50, 25);
		txtProductQuality.setText(productEvaluated.getQuality().toString());
		txtProductQuality.setHorizontalAlignment(SwingConstants.RIGHT);
		txtProductQuality.setEditable(false);
		contentPane.add(txtProductQuality);
		contentPane.add(createLabelQuality(productEvaluated.getQuality(),
				txtProductQuality.getX() + TEXTFIELD_WIDTH + SPACE,
				txtProductQuality.getY() + SPACE));
		
		JSeparator separator = new JSeparator();
		separator.setBounds(442, 39, 430, 2);
		contentPane.add(separator);
		
		JButton btnCancel = new JButton("Cancelar");
		btnCancel.setBounds(781, 314, 91, 25);
		getContentPane().add(btnCancel);
		
		JTreeTable treeTable = new JTreeTable(new Model(productEvaluated));
		
		JScrollPane scrollPaneTreeTable = new JScrollPane(treeTable);
		scrollPaneTreeTable.setBounds(10, 11, 422, 328);
		contentPane.add(scrollPaneTreeTable);
		
		btnCancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				EvaluationModal.this.dispose();
			}
		});
	}
	
	private JLabel createLabelQuality(BigDecimal quality, int x, int y) {
		JLabel lblQuality = new JLabel();
		lblQuality.setBounds(x, y, 18, 18);

		IconEnum icon = null;
		RankEnum rank = RankEnum.determinateRank(quality);

		if (rank != null) {
			switch (rank) {
			case BAD:
				icon = IconEnum.CROSS;
				break;
			case REGULAR:
				icon = IconEnum.WARN;
				break;
			case ACCEPTABLE:
				icon = IconEnum.TICK;
				break;
			case EXCELLENT:
				icon = IconEnum.TICK;
			}			
		}
		
		lblQuality.setIcon(getIcon(icon));
		lblQuality.setToolTipText(rank.toString());

		return lblQuality;
	}
	
	private void createFunctionalityQuality(JPanel panelCharacteristicsQuality,
			int[] coordinate) {
		JLabel lblFunctionalityQuality = new JLabel("Funcionalidad:");
		lblFunctionalityQuality.setBounds(coordinate[0], coordinate[1],
				LABEL_WIDTH, LABEL_HEIGHT);
		panelCharacteristicsQuality.add(lblFunctionalityQuality);

		BigDecimal functionalityQuality = productEvaluated.getCharacteristics()
				.get(CharacteristicEnum.FUNCTIONALITY).getQuality();

		txtFunctionalityQuality = new JTextField();
		txtFunctionalityQuality.setEditable(false);
		txtFunctionalityQuality.setText(functionalityQuality.toString());
		txtFunctionalityQuality.setHorizontalAlignment(SwingConstants.RIGHT);		
		txtFunctionalityQuality.setBounds(coordinate[0] + LABEL_WIDTH + SPACE,
				coordinate[1] - SPACE, TEXTFIELD_WIDTH, TEXTFIELD_HEIGHT);
		panelCharacteristicsQuality.add(txtFunctionalityQuality);
		panelCharacteristicsQuality.add(createLabelQuality(
				functionalityQuality, txtFunctionalityQuality.getX()
				+ TEXTFIELD_WIDTH + SPACE, coordinate[1] + 2));
	}

	private void createReliabilityQuality(JPanel panelCharacteristicsQuality,
			int[] coordinate) {
		JLabel lblReliabilityQuality = new JLabel("Fiabilidad:");
		lblReliabilityQuality.setBounds(coordinate[0], coordinate[1],
				LABEL_WIDTH, LABEL_HEIGHT);
		panelCharacteristicsQuality.add(lblReliabilityQuality);
		
		BigDecimal reliabilityQuality = productEvaluated.getCharacteristics()
				.get(CharacteristicEnum.RELIABILITY).getQuality();
		
		txtReliabilityQuality = new JTextField();
		txtReliabilityQuality.setEditable(false);
		txtReliabilityQuality.setText(reliabilityQuality.toString());
		txtReliabilityQuality.setHorizontalAlignment(SwingConstants.RIGHT);
		txtReliabilityQuality.setBounds(coordinate[0] + LABEL_WIDTH + SPACE,
				coordinate[1] - SPACE, TEXTFIELD_WIDTH, TEXTFIELD_HEIGHT);
		panelCharacteristicsQuality.add(txtReliabilityQuality);
		panelCharacteristicsQuality.add(createLabelQuality(
				reliabilityQuality, txtReliabilityQuality.getX()
				+ TEXTFIELD_WIDTH + SPACE, coordinate[1] + 2));		
	}
	
	private void createUsabilityQuality(JPanel panelCharacteristicsQuality,
			int[] coordinate) {
		JLabel lblUsabilityQuality = new JLabel("Usabilidad:");
		lblUsabilityQuality.setBounds(coordinate[0], coordinate[1],
				LABEL_WIDTH, LABEL_HEIGHT);
		panelCharacteristicsQuality.add(lblUsabilityQuality);
		
		BigDecimal usabilityQuality = productEvaluated.getCharacteristics()
				.get(CharacteristicEnum.USABILITY).getQuality();

		txtUsabilityQuality = new JTextField();
		txtUsabilityQuality.setEditable(false);
		txtUsabilityQuality.setText(usabilityQuality.toString());
		txtUsabilityQuality.setHorizontalAlignment(SwingConstants.RIGHT);
		txtUsabilityQuality.setBounds(coordinate[0] + LABEL_WIDTH + SPACE,
				coordinate[1] - SPACE, TEXTFIELD_WIDTH, TEXTFIELD_HEIGHT);
		panelCharacteristicsQuality.add(txtUsabilityQuality);
		panelCharacteristicsQuality.add(createLabelQuality(
				usabilityQuality, txtUsabilityQuality.getX()
				+ TEXTFIELD_WIDTH + SPACE, coordinate[1] + 2));		
	}

	private void createEfficiencyQuality(JPanel panelCharacteristicsQuality,
			int[] coordinate) {
		JLabel lblEfficiencyQuality = new JLabel("Eficiencia:");
		lblEfficiencyQuality.setBounds(coordinate[0], coordinate[1],
				LABEL_WIDTH, LABEL_HEIGHT);
		panelCharacteristicsQuality.add(lblEfficiencyQuality);
		
		BigDecimal efficiencyQuality = productEvaluated.getCharacteristics()
				.get(CharacteristicEnum.EFFICIENCY).getQuality();

		txtEfficiencyQuality = new JTextField();
		txtEfficiencyQuality.setEditable(false);
		txtEfficiencyQuality.setText(efficiencyQuality.toString());
		txtEfficiencyQuality.setHorizontalAlignment(SwingConstants.RIGHT);
		txtEfficiencyQuality.setBounds(coordinate[0] + LABEL_WIDTH + SPACE,
				coordinate[1] - SPACE, TEXTFIELD_WIDTH, TEXTFIELD_HEIGHT);
		panelCharacteristicsQuality.add(txtEfficiencyQuality);
		panelCharacteristicsQuality.add(createLabelQuality(efficiencyQuality,
				txtEfficiencyQuality.getX() + TEXTFIELD_WIDTH + SPACE,
				txtEfficiencyQuality.getY() + 2));
	}

	private void createMaintainabilityQuality(
			JPanel panelCharacteristicsQuality, int[] coordinate) {
		JLabel lblMaintainabilityQuality = new JLabel("Mantenibilidad:");
		lblMaintainabilityQuality.setBounds(coordinate[0], coordinate[1],
				LABEL_WIDTH, LABEL_HEIGHT);
		panelCharacteristicsQuality.add(lblMaintainabilityQuality);
		
		BigDecimal maintainabilityQuality = productEvaluated.getCharacteristics()
				.get(CharacteristicEnum.MAINTAINABILITY).getQuality();
		
		txtMaintainabilityQuality = new JTextField();
		txtMaintainabilityQuality.setEditable(false);
		txtMaintainabilityQuality.setText(maintainabilityQuality.toString());
		txtMaintainabilityQuality.setHorizontalAlignment(SwingConstants.RIGHT);
		txtMaintainabilityQuality.setBounds(coordinate[0] + LABEL_WIDTH + SPACE,
				coordinate[1] - SPACE, TEXTFIELD_WIDTH, TEXTFIELD_HEIGHT);
		panelCharacteristicsQuality.add(txtMaintainabilityQuality);
		panelCharacteristicsQuality.add(createLabelQuality(
				maintainabilityQuality, txtMaintainabilityQuality.getX()
				+ TEXTFIELD_WIDTH + SPACE, coordinate[1] + 2));				
	}

	private void createPortabilityQuality(JPanel panelCharacteristicsQuality,
			int[] coordinate) {
		JLabel lblPortabilityQuality = new JLabel("Portabilidad:");
		lblPortabilityQuality.setBounds(coordinate[0], coordinate[1],
				LABEL_WIDTH, LABEL_HEIGHT);
		panelCharacteristicsQuality.add(lblPortabilityQuality);
		
		BigDecimal portabilityQuality = productEvaluated.getCharacteristics()
				.get(CharacteristicEnum.PORTABILITY).getQuality();
				
		txtPortabilityQuality = new JTextField();
		txtPortabilityQuality.setEditable(false);
		txtPortabilityQuality.setText(portabilityQuality.toString());
		txtPortabilityQuality.setHorizontalAlignment(SwingConstants.RIGHT);
		txtPortabilityQuality.setBounds(coordinate[0] + LABEL_WIDTH + SPACE,
				coordinate[1] - SPACE, TEXTFIELD_WIDTH, TEXTFIELD_HEIGHT);
		panelCharacteristicsQuality.add(txtPortabilityQuality);
		panelCharacteristicsQuality.add(createLabelQuality(
				portabilityQuality, txtPortabilityQuality.getX()
				+ TEXTFIELD_WIDTH + SPACE, coordinate[1] + 2));						
	}
	
	private void calculateCoordinates() {
		int size = productEvaluated.getCharacteristics().size();
		int xtemp = 15;
		int ytemp = 30;

		int count = 0;
		for (int i = 0; i < size; i++) {
			if (count > 1) {
				xtemp = 15;
				ytemp += 32;
				count = 0;
			}

			int[] xy = { xtemp, ytemp };
			coordinates[i] = xy;
			xtemp += 190;
			count++;
		}
	}
	
	private ImageIcon getIcon(IconEnum icon) {
		return new ImageIcon(getClass().getResource(icon.getLocation()));
	}
	
	private void save(HSSFWorkbook book) {
		JFileChooser fileChooser = new JFileChooser();
		FileNameExtensionFilter filter = new FileNameExtensionFilter(
				"Libro de Excel", "xls");
		fileChooser.setDialogTitle("Guardar");
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		fileChooser.addChoosableFileFilter(filter);

		int option = fileChooser.showSaveDialog(this);
		// Process the results.
		if (option == JFileChooser.APPROVE_OPTION) {
			File file = fileChooser.getSelectedFile();
			String ext = "";
			if (fileChooser.getFileFilter() == filter) {
				String extension = file.getAbsolutePath();
				if (!extension.endsWith(".xls")) {
					ext = ".xls";
				}
			}

			try {
				OutputStream output = new FileOutputStream(file + ext);
				book.write(output);
				output.close();
			} catch (Exception ex) {
				Logger.getInstance().registrarLog(ex);
			}
			
			JOptionPane.showMessageDialog(this,
					"Se ha exportado el reporte correctamente",
					"Mensaje de éxito", JOptionPane.INFORMATION_MESSAGE);
		}
	}
}
	

